import getpath
import os
import openpyxl
from openpyxl.drawing.image import Image
from PyQt5 import QtWidgets
import io
from PIL import Image as PILImage
# from typing import Tuple
from sample import SampleICP
import myglobal
import logging
doc=None
filename=None
curvePage=-1
def getimages():
    folder=os.path.split(os.path.abspath(filename))[0]
    pimgs=[]
    for one in doc.find_all("img"):
        print(one,dir(one))
        print(one.attrs["src"])
        pimgs.append(os.path.join(folder,one.attrs["src"]))
    return pimgs[1:]
def getimageTabls_raw():
    tbs=[]
    for one in doc.body.contents:
        # print(dir(one))    
        if one.name=="table":
            tbs.append(one)
    return tbs[2:-2]
def T(a):
    b=[]
    for i in range(len(a[0])):
        b.append([])
    for i in range(len(a)):
        one=a[i]
        for j in range(len(one)):#cell in one:
            b[j].append(one[j])
    return b
def addOne(data,one):
    if len(data)==0:#first
        r=one
    else:
        r=np.concatenate((data,one),axis=1)
    return r
 
def addOneAxis0(data,one):
    if len(data)==0:#first
        r=one
    else:
        r=data+one[1:]#remove first title row
    return r    
def getdata(file_name):
    from bs4 import BeautifulSoup
    global doc,filename
    filename=file_name
    fcontent=open(file_name,encoding="utf-8").read()
    doc = BeautifulSoup(fcontent,"html.parser")
    tbs=doc.find_all("table")#,attrs={"role":"grid"})
    data=[]
    table=tbs[-2]
    allr=table.find_all("tr")
    onerow=[]
    for col in allr[0].find_all('th'):
        onerow.append(col.text)
    data.append(onerow)
    for row in allr[1:]:
        onerow=[]
        for col in row.find_all('td'):
            onerow.append(col.text)
        data.append(onerow)
    items = data[0][4:]
    for i in range(len(items)):
        fs=items[i].split(" ")
        ele=fs[0]
        wave=fs[1]
        items[i] = (ele, wave)
    at = 1
    rt=[]
    while True:
        try:
            s=SampleICP()
            s.num=at
            s.sampleid = data[at][0].replace('\n', '')
            s.mass ="%.04f" % (myglobal.myfloat(data[at][2])/10)
            s.volume =str(myglobal.myfloat(data[at][3])*100)
            s.xishi = ""
            logging.info(s.sampleid)
            ii=0
            for one in data[at][4:]:
                print(one,items[ii])
                s.items[items[ii]]=one
                print(s.items)
                ii+=1
            if s.sampleid == "":
                break
            logging.info(s.items)
            rt.append(s)
            at+=1
        except IndexError:
            break        
    return rt
def output(ts,fname):
    f=open(fname,'w')
    for one in ts:
        line=",".join(one)
        line=line.replace("\n","")
        f.write(line+"\n")
    f.close()
def output_curve(ws,hang):#outputsheet,pdf filename,0-n page
    ts=getimageTables()
    outputImages(ts,ws,hang)
def outputImages(ts,ws,hang):#outputsheet,pdf filename,0-n page
    ss=QtWidgets.qApp.screens()
    if len(ss)<1:
        rowh=13.5/72.0*96
    else:
        rowh=13.5/72.0*ss[0].physicalDotsPerInch() #bang to pixel
    for i in range(len(ts)):
        (img,paras)=ts[i]
        folder=os.path.split(os.path.abspath(filename))[0]
        img = Image(os.path.join(folder,img))
        img.width=300#not too big
        img.height=200
        # print(dir(img))
        n=int((img.height)/rowh)
        at_row=i*n+hang
        for j in range(len(paras)):
            ws["A"+str(at_row+j)]=paras[j]
        ws.column_dimensions['A'].width = 30.0
        ws.add_image(img, "B"+str(at_row))  # 图片 插入 A1 的位置上
def test1():
    global filename
    filename=r"..\data\iCAP PRO\iCAP PRO.html"
    (data,mass)=getDataAndMass(filename)
    geti()
def getimageTables():
    tbs=[]
    for one in doc.body.contents:
        if one.name=="table":
            tbs.append(one)
    its=tbs[2:-2]
    r2=[]
    for one in its:
        r=getImageTable_row(one)
        for one in r:
            r2.append(one)
    return r2
def getImageTable_row(one):
    r=[]
    for t in one.find_all("table"):
        r.append(getImageTable_one(t))
    return r
def getImageTable_one(one):
    rows=one.find_all("tr")
    paras=[rows[0].text.replace("\n","")]
    for one in rows[2:]:
        paras.append(one.text.replace("\n",""))
    img=rows[1].find("img").attrs["src"]
    return(img,paras)
def geti():
    wb = openpyxl.Workbook()
    ws = wb.active
    output_curve(ws,1)
    wb.save("imags.xlsx")
def test_getdata():
    fname=os.path.join(getpath.getpath(),"..","data","iCAP PRO","iCAP PRO.html")#"6300.xls")
    data=getdata(fname)
    # print(data)
    return data
if __name__=="__main__":
    data=test_getdata()
